<?php
namespace app\admin\model;

use think\Model;

class User extends Model
{
    protected function initialize(){
        parent::initialize();
    }
    
//     protected $name = 'user';
    public function checkLoginUser(array $user_info){
        $result = db('user')->where([
            'user_name' => $user_info['name'],
            'password' => $user_info['password']
        ])->value('id');
        return $result;   
    }
    
    public function saveAdmin(array $user_info)
    {
        $user = new User();
        $data = [
            'user_name' => $user_info['user_name'],
            'modules_power' => $user_info['modules_power'],
        ];
        if (isset($user_info['password'])){
            $data['password'] = $user_info['password'];
        }
        
        if (isset($user_info['id'])){
            $result = $user->save($data,['id'=>$user_info['id']]);
        }else {
            $result = $user->save($data);
        }
        
        return $result;
    }
    
    public function getModules($user_id)
    {
        $modules_power = db('user')->where('id',$user_id)->value('modules_power');
        if ($modules_power == false || empty($modules_power)){
            return false;
        }
        $modules = array();
        if ($modules_power == 'all'){
            $modules = db('modules')->select();
        }else {
            $modules_power = json_decode($modules_power);
            foreach ($modules_power as $k => $v){
                $modules[$k]=db('modules')->where('id',$v)->find();
                if ($modules[$k] == false || empty($modules[$k])){
                    return false;
                }
            }
        }
        
        foreach ($modules as $kk => $vv){
            $modules[$kk]['submodules'] = db('submodules')->where('parent_id',$modules[$kk]['id'])->select(); 
        }
        return $modules;
    }
    
  
}